﻿using SqlSugar;
using System.Reflection;

namespace Koala.Pro.Core;

[Serializable]
public abstract class Entity : Entity<int>, IEntity, IEntity<int>
{
    [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
    public override int Id { get; set; }
}


[Serializable]
public abstract class Entity<TPrimaryKey> : IEntity<TPrimaryKey>
{
    [SugarColumn(IsPrimaryKey = true, ColumnDescription = "主键")]
    public virtual TPrimaryKey Id { get; set; }

    public virtual bool IsTransient()
    {
        if (EqualityComparer<TPrimaryKey>.Default.Equals(Id, default))
        {
            return true;
        }
        if (typeof(TPrimaryKey) == typeof(int))
        {
            return Convert.ToInt32(Id) <= 0;
        }
        if (typeof(TPrimaryKey) == typeof(long))
        {
            return Convert.ToInt64(Id) <= 0;
        }
        return false;
    }

    public virtual bool EntityEquals(object obj)
    {
        if (obj == null || !(obj is Entity<TPrimaryKey>))
        {
            return false;
        }
        if (this == obj)
        {
            return true;
        }
        Entity<TPrimaryKey> entity = (Entity<TPrimaryKey>)obj;
        if (IsTransient() && entity.IsTransient())
        {
            return false;
        }
        Type type = GetType();
        Type type2 = entity.GetType();
        if (!IntrospectionExtensions.GetTypeInfo(type).IsAssignableFrom(type2) && !IntrospectionExtensions.GetTypeInfo(type2).IsAssignableFrom(type))
        {
            return false;
        }
        return Id.Equals(entity.Id);
    }

    public override string ToString()
    {
        return $"[{GetType().Name} {Id}]";
    }
}

